package com.yifeng.controller;

import com.yifeng.po.User;
import com.yifeng.util.AjaxResult;
import com.yifeng.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @Decription :
 * author : yifeng
 * 创建时间 ：2019/1/17 :10:07
 * version : 1.0
 */
@Controller
public class LoginController {

    @RequestMapping(value="/login", method= RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public AjaxResult login(@RequestBody Map map) {
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        // 1）创建LoginConroller,写一个方法接收前台登录请求并接受登录信息(用户名和密码)
        // 2）获取当前的 Subject. 调用 SecurityUtils.getSubject();
        Subject currentUser = SecurityUtils.getSubject();
        // 3）测试当前的用户是否已经被认证. 即是否已经登录. 调用 Subject 的 isAuthenticated()
        if (!currentUser.isAuthenticated()) {
            // 4）若没有被认证, 则把用户名和密码封装为 UsernamePasswordToken 对象
            UsernamePasswordToken upt = new UsernamePasswordToken(username, password);
            // 5）执行登录: 调用 Subject 的 login(AuthenticationToken) 方法.
            try {
                currentUser.login(upt);
            }
            catch (UnknownAccountException e) {
                e.printStackTrace();
                return new AjaxResult("用户名或密码不正确！" + e.getMessage());
            }
            catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                return new AjaxResult("用户名或密码不正确！" + e.getMessage());
            }
            catch (LockedAccountException e) {
                e.printStackTrace();
                return new AjaxResult("账号被锁定！" + e.getMessage());
            }
            catch (AuthenticationException e) {
                e.printStackTrace();
                return new AjaxResult("登录失败！" + e.getMessage());
            }
        }
        //用户登录成功后，要存放用户到Session
        User principal = (User) currentUser.getPrincipal();
        System.out.println(principal);
        UserContext.setUser(principal);
        System.out.println("jjjjj"+UserContext.getUser());
        return new AjaxResult();
    }
}
